package cn.liwq.demo.disruptor;

import cn.hutool.core.util.RandomUtil;
import com.lmax.disruptor.WorkHandler;
import com.lmax.disruptor.dsl.Disruptor;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author lweiqiang
 * @date 2023/5/4
 */
@Slf4j
@AllArgsConstructor
public class TaskEventHandler implements WorkHandler<TaskEvent> {
    //    @Override
    //    public void onEvent(TaskEvent taskEvent, long l, boolean b) throws Exception {
    //        log.info("{}-{}", l, taskEvent.getContent());
    //        long num = RandomUtil.randomLong(5L);
    //        TimeUnit.SECONDS.sleep(num);
    //        if (num % 2 == 0) {
    //            throw new RuntimeException("handle error");
    //        }
    //    }

    private Disruptor<TaskEvent> disruptor;

    @Override
    public void onEvent(TaskEvent taskEvent) throws Exception {
        log.info("start handling: {}-{}", taskEvent.getId(), taskEvent.getContent());
        TimeUnit.SECONDS.sleep(2L);
        taskEvent.setResult(taskEvent.getId() + taskEvent.getContent());
        long num = RandomUtil.randomLong(5L);
        TimeUnit.SECONDS.sleep(num);
        if (num % 2 == 0) {
            disruptor.halt();
            //            throw new RuntimeException("handle error");
        }
        log.info("{} - done", taskEvent.getId());
    }
}
